<?php
namespace app\apiadmin\middleware;

use think\facade\Config;
use think\facade\Log;
use app\common\utils\Crypter;

/**
 * 验证中间件
 */
class AuthInit
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        // 前置中间件，前置中间件优先于路由，所以获取不到 controller 或 action，只能判断路径
        $pathinfo = $request->pathinfo();
        // var_dump($request->header()); die("");

        // 非index控制器，都必须验证权限
        if (!preg_match("/^index/i", strtolower($pathinfo))) {
            // 验证auth
            $header = $request->header();
            if (empty($header['authorization'])) {
                return json(errorful("缺少auth签名"));
            }
            $authorization = $header['authorization'];
 
            // 解密
            $opensslkey = trim(Config::get("auth.opensslkey"));
            $decrypt    = (new Crypter($opensslkey))->decrypt($authorization);
            if ($decrypt) {
                $decrypt_array = json_decode($decrypt, true);
                if (empty($decrypt_array['id'])) {
                    return json(errorful("签名内容错误"));
                }
            } else {
                return json(errorful("签名解析错误"));
            }
        }

        // 日志
        Log::record($request->server("REMOTE_ADDR") . " " . $request->server("REQUEST_URI"));

        return $next($request);
    }
}
